

<template>

    <basic-container>
      <avue-crud
        ref="crud"
        :option="tableOption"
        :data="list"
        :page="page"
        v-model="form"
        :table-loading="listLoading"
        :permission="permissionList"
        @on-load="getList"
        @search-change="searchChange"
        @search-reset="searchReset"
        @refresh-change="refreshChange"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @row-del="rowDel"
        @row-update="rowUpdate"
        @row-save="rowSave"
      >

        <template slot="menuLeft">
          <el-button type="danger"
                     size="small"
                     icon="el-icon-delete"
                     plain
                     v-if="permissions.sys_role_del"
                     @click="handleDelete">删 除
          </el-button>
        </template>

        <template
          slot="menu"
          slot-scope="scope">
          <el-button
            v-if="permissions.sys_role_perm"
            type="text"
            size="mini"
            icon="el-icon-plus"
            @click="handlePermission(scope.row,scope.index)">权限
          </el-button>
        </template>
      </avue-crud>

      <el-dialog
        :visible.sync="dialogPermissionVisible"
        :close-on-click-modal="false"
        width="20%"
        title="分配权限">

        <el-tabs v-model="activeName" type="border-card">
          <el-tab-pane label="菜单权限">
            <div class="dialog-main-tree">
              <el-tree
                ref="menuTree"
                :data="treeData"
                :default-checked-keys="checkedKeys"
                :check-strictly="false"
                :props="defaultProps"
                :filter-node-method="filterNode"
                class="filter-tree"
                node-key="id"
                highlight-current
                show-checkbox/>
            </div>
          </el-tab-pane>
          <el-tab-pane label="数据权限">
            <div class="dialog-main-tree">
              <el-tree
                ref="dataRuleTree"
                :data="dataRuleData"
                :default-checked-keys="checkedRoleDataKeys"
                :check-strictly="false"
                :props="defaultProps"
                :filter-node-method="filterNode"
                class="filter-tree"
                node-key="id"
                highlight-current
                show-checkbox/>
            </div>

          </el-tab-pane>
        </el-tabs>

        <div slot="footer"
             class="dialog-footer">
          <el-button
            type="primary"
            size="small"
            @click="updatePermession(roleId)">更 新
          </el-button>
          <el-button
            type="default"
            size="small"
            @click="cancal()">取消</el-button>
        </div>
      </el-dialog>
    </basic-container>

</template>

<script>
  import { addObj, delObj, fetchList, fetchRoleTree,fetchRoleDataRuleTree, permissionUpd, permDataRuleUpd, putObj } from '@/api/admin/role'
  import { tableOption } from '@/const/crud/admin/role'
  import { fetchMenuTree, fetchDataRuleTree } from '@/api/admin/menu'
  import { mapGetters } from 'vuex'

  export default {
    name: 'TableRole',
    data() {
      return {
        searchForm: {},
        tableOption: tableOption,
        dsScopeData: [],
        treeData: [],
        checkedKeys: [],
        dataRuleData: [],
        checkedRoleDataKeys: [],
        checkedDsScope: [],
        defaultProps: {
          label: 'name',
          value: 'id'
        },
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        selectionList: [],
        activeName: '',
        menuIds: '',
        dataRuleIds: '',
        list: [],
        listLoading: true,
        form: {},
        roleId: undefined,
        roleCode: undefined,
        rolesOptions: undefined,
        dialogPermissionVisible: false
      }
    },

    computed: {
      ...mapGetters(['elements', 'permissions']),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permissions['sys_role_add'], false),
          delBtn: this.vaildData(this.permissions['sys_role_del'], false),
          editBtn: this.vaildData(this.permissions['sys_role_edit'], false),
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      getList(page, params) {
        this.listLoading = true
        fetchList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params, this.searchForm)).then(response => {
          this.list = response.data.data.records
          this.page.total = response.data.data.total
          this.listLoading = false
        }).catch(() => {
          this.listLoading = false
        })
      },
      searchChange(form, done) {
        this.searchForm = form;
        this.page.currentPage = 1;
        this.getList(this.page, form)
        done();
      },
      searchReset() {
        this.searchForm = {};
        this.getList(this.page)
      },

      refreshChange() {
        this.getList(this.page,this.searchForm)
      },

      cancal () {
        this.dialogPermissionVisible = false;
      },
      handlePermission(row) {
        fetchRoleTree(row.id)
          .then(response => {
            this.checkedKeys = response.data.data
            return fetchMenuTree()
          })
          .then(response => {
            this.treeData = response.data.data
            this.dialogPermissionVisible = true
            this.roleId = row.id
            this.roleCode = row.roleCode
          })

        fetchRoleDataRuleTree(row.id)
          .then(response => {
            this.checkedRoleDataKeys = response.data.data
            return fetchDataRuleTree()
          })
          .then(response => {
            this.dataRuleData = response.data.data
          })
      },
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      getNodeData(data, done) {
        done()
      },

      rowSave(row, done, loading) {
        addObj(this.form).then(() => {
          this.getList(this.page)
          done()
          this.$notify.success('创建成功')
        }).catch(() => {
          loading()
        })
      },
      rowUpdate(row, index, done, loading) {
        putObj(this.form).then(() => {
          this.getList(this.page)
          done()
          this.$notify.success('修改成功')
        }).catch(() => {
          loading()
        })
      },
      rowDel(row) {
        this.$confirm('是否确认删除名称为"' + row.roleName + '"' + '"的数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delObj(row.id)
        }).then(() => {
          this.getList(this.page)
          this.$notify.success('删除成功')
        })
      },

      selectionChange(list) {
        this.selectionList = list;
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },

      updatePermession (roleId) {
        this.menuIds = ''
        this.dataRuleIds = ''
        if (this.activeName == '0'){
          this.menuIds = this.$refs.menuTree.getCheckedKeys().join(',').concat(',').concat(this.$refs.menuTree.getHalfCheckedKeys().join(','))
          permissionUpd(roleId, this.menuIds).then(() => {
            this.dialogPermissionVisible = false
            this.$store.dispatch('GetMenu', {type:false})
            this.$notify.success('菜单权限修改成功')
          })
        } else if (this.activeName == '1') {
          this.dataRuleIds = this.$refs.dataRuleTree.getCheckedKeys().join(',').concat(',').concat(this.$refs.dataRuleTree.getHalfCheckedKeys().join(','))
          console.log(this.dataRuleIds);
          permDataRuleUpd(roleId, this.dataRuleIds).then(() => {
            this.dialogPermissionVisible = false
            this.$store.dispatch('GetMenu', {type:false})
            this.$notify.success('数据权限修改成功')
          })
        }

      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return delObj(this.ids);
          })
          .then(() => {
            this.getList(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      }

    }
  }
</script>

<style>
</style>
